<template>
	<view>
		<view>
			<u-navbar :is-back="true" :title="supplierInfo.shopName" class="titleBar">
				<view slot="right" class="slot-wrap">
					<view class="btn" @click.stop="JumpToPage()">
						店铺
					</view>

				</view>
			</u-navbar>

			<!--:style="{height: style.contentViewHeight + 'px'}"-->

			<view class="content" id="content">
				<view class="loading-box" v-if="!loading">
					<u-loading mode="flower"></u-loading>
				</view>

				<view class="box">
					<scroll-view id="scrollview" class="chat-window" scroll-y="true" :style="{height: style.contentViewHeight + 'px'}"
					 :scroll-with-animation="scrollAnimation" :scroll-top="scrollTop" @scrolltoupper='scroTopHandle'>

						<view v-for="(item,index) of chatList" class="chatItem" :key="index">

							<view v-if="userInfo.id != item.fromUserId">
								<view class="chart-timer">
									{{item.messages.timestamp}}
								</view>
								<view class="item left">
									<img class="header-img" :src="item.messages.fromUserHead" />
									<view class="message" v-if="item.messages.type == 'text'">{{item.messages.msg}}</view>
									<view class="message-image-left" mode='aspectFit' v-else>
										<image :src='item.messages.msg' @click="previewImage(item.messages.msg)" class="imgItem" />
									</view>
								</view>

							</view>

							<!--自己为右边-->
							<view class="item right" v-else>
								<img class="header-img" :src="item.messages.fromUserHead" />
								<view class="message" style="background-color: #1677FF;color: #FFFFFF" v-if="item.messages.type == 'text'">{{item.messages.msg}}</view>
								<view class="message-image-right" mode='aspectFit' v-else>
									<image :src='item.messages.msg' @click="previewImage(item.messages.msg)" class="imgItem" />
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
				<div class="input-box">
					<image src="@/static/message_img.png" @click="uploadImg()" class="iconImg">
					</image>
					<input type="text" v-model="message" class="uni-input" @confirm="handeSendMessge('text')" />
					<u-button type="primary" size="mini" style="height: 24px" @click="handeSendMessge('text')">发送</u-button>
				</div>
			</view>
		</view>

	</view>
</template>

<script>
	import io from '@/common/weapp.socket.io'

	export default {
		data() {
			return {
				scrollTop: 0,
				scrollAnimation: false,
				loading: true, //标识是否正在获取数据
				style: {
					pageHeight: 0,
					contentViewHeight: 0,
					footViewHeight: 90,
					mitemHeight: 0
				},
				message: "",
				toUserId: "",
				formUserId: "",
				chatList: [],
				supplierInfo: {},
				userInfo: {},
				fileImage: '',
				shopName: '',
				query: {
					limit: 10,
					offset: 1,
					userId: '',
					role: 'user'
				},
				conversationId: "",
				backTextStyle: {
					width: "22px",
					height: " 22px",
					color: '#d95fd4'
				},
				supplierUserId: ''
			}
		},
		onLoad(data) {
			this.supplierInfo = uni.getStorageSync('supplierInfo_chat');
			this.supplierUserId = data.supplierUserId
			this.conversationId = data.conversationId
			this.supplierId = data.supplierId
			//遗留问题
			this.userInfo = JSON.parse(uni.getStorageSync('userInfo'))
			this.query.userId = this.userInfo.id
			this.getHistoryMessage()
			// 监听广播消息
			//this.getLatestMsg()

		},
		methods: {
			// 上传图片
			uploadImg() {
				var _self = this;
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: function(res) {
						const tempFilePaths = res.tempFilePaths;

						const uploadTask = uni.uploadFile({
							url: _self.$BASE_URL + '/api/upload',
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								'user': 'test'
							},
							success: function(uploadFileRes) {
								_self.fileImage = JSON.parse(uploadFileRes.data).url
								_self.handeSendMessge('image')

							}
						});

						uploadTask.onProgressUpdate(function(res) {
							_self.percent = res.progress;
							console.log('上传进度' + res.progress);
							console.log('已经上传的数据长度' + res.totalBytesSent);
							console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
						});
					},
					error: function(e) {
						console.log(e);
					}
				})
			},


			// 顶部触发
			scroTopHandle(e) {
				console.log('顶部触发')

				this.query.limit = 8
				this.query.offset++;
				setTimeout(() => {
					//TODO这里填写你加载数据的方法
					this.getHistoryMessage("scroll");

				}, 300)

			},
			getLatestMsg(content) {
				// 注意不要弄反角色

				let data = {
					toUserId: this.userInfo.id,
					toUserName: this.userInfo.userName,
					toUserHead: this.userInfo.headimgurl,
					conversationId: this.conversationId,
					fromUserId: this.supplierInfo.userId,
					fromUserName: this.supplierInfo.shopName,
					fromUserHead: this.supplierInfo.shopLogo.length > 0 ? this.supplierInfo.shopLogo[0].url : "",
				}

				data.messages = JSON.parse(content)

				this.chatList.push(data)
				this.scrollToBottom()




			},
			// 预览图片
			previewImage(value) {
				let arr = []
				arr.push(value) // url必须是数组格式
				uni.previewImage({
					current: 0,
					urls: arr
				})
			},


			// 发送消息
			handeSendMessge(fileType) {

				let data = {
					toUserId: this.supplierInfo.userId,
					toUserName: this.supplierInfo.shopName,
					toUserHead: this.supplierInfo.shopLogo.length > 0 ? this.supplierInfo.shopLogo[0].url : "",
					type: fileType,
					conversationId: this.conversationId,
					msg: fileType == 'text' ? this.message : this.fileImage,
					fromUserId: this.userInfo.id,
					fromUserName: this.userInfo.userName,
					fromUserHead: this.userInfo.headimgurl
				}

				if (fileType == 'text') {
					if (this.message == '') return
				} else {
					if (this.fileImage == '') return
				}

				// this.socket.emit('exchange',data)
				this.$eventHub.$emit('sendMessage', data)

				data.messages = data
				//data.timestamp=''
				this.message = ''
				this.chatList.push(
					data
				)
				this.scrollToBottom()

			},

			getHistoryMessage(type) {

				if (!this.loading) return
				this.loading = false

				this.$http
					.post('/api/jump', {
						url: '/api/chat/list/' + this.conversationId,
						method: 'get',
						parameter: this.query
					})
					.then(res => {
						if (res.data.code == 20000) {
							this.chatList = res.data.data.reverse().concat(this.chatList)
							var that = this
							setTimeout(() => {
								that.loading = true
							}, 300)
							// 滚动到底部
							if (type != "scroll") {
								this.$nextTick(function() {
									this.scrollTop = 9999;
									this.scrollAnimation = true;
								});
							}
						} else {
							uni.showToast({
								title: res.data.msg ? res.data.msg : '请求失败',
								icon: 'none'
							})
						}




					});
			},
			// 店铺跳转
			JumpToPage() {
				uni.navigateTo({
					url: '../../pages/store/index?id=' + this.supplierUserId,
				})
			},

			scrollToBottom() {

				let that = this
				let query = uni.createSelectorQuery()
				query.selectAll('.chatItem').boundingClientRect()
				query.select('#scrollview').boundingClientRect()
				query.exec((res) => {

					that.style.mitemHeight = 0;
					res[0].forEach(element => {
						that.style.mitemHeight = that.style.mitemHeight + element.height + 40
						setTimeout(() => {
							if (that.style.mitemHeight > (that.style.contentViewHeight - 100)) {
								that.scrollTop = that.style.mitemHeight - that.style.contentViewHeight
							}
						}, 100)



					});
				})
			},
		},
		created() {
			var that = this
			this.$eventHub.$on('acceptMessage', function(data) {
				console.log(data)
				that.getLatestMsg(data)
			});


			const res = uni.getSystemInfoSync(); //获取手机可使用窗口高度     api为获取系统信息同步接口
			this.style.pageHeight = res.windowHeight;
			this.style.contentViewHeight = res.windowHeight - uni.getSystemInfoSync().screenWidth / 750 * (100) - 70





		},
	}
</script>

<style scoped>
	.slot-wrap {
		display: flex;
		justify-content: center;
		padding: 0 30rpx;
		align-items: center;
	}

	.btn {
		width: 72px;
		/* background: #1677FF; */
		border-radius: 13px;
		color: #1677FF;
		text-align: center;
		padding: 0 4px;
		border: 1px solid #1677FF;
	}


	.item {
		display: flex;
		margin-bottom: 10px;
	}

	.left {
		flex-direction: row;
		margin-left: 15px;
		display: flex;
		align-items: center;
	}

	.right {
		flex-direction: row-reverse;
		margin-right: 15px;
		margin-top: 12px;
		display: flex;
		align-items: center;
	}

	.right .message {
		margin-right: 10px;
	}

	.right .imgItem {
		width: 200rpx;
		height: 300rpx;
		border-radius: 8px;
		margin-right: 15px;

	}

	.left .message {
		margin-left: 10px;
	}

	.left .imgItem {
		width: 200rpx;
		height: 300rpx;
		border-radius: 8px;
		margin-left: 15px;
	}

	.header-img {
		width: 40px;
		height: 40px;
		border-radius: 100px;
	}

	.message {
		border-radius: 10px;
		display: flex;
		background: #FFFFFF;
		min-height: 25px;
		padding: 9px 10px;
		align-items: center;
		width: 234px;
		font-size: 13px;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #333333;
		line-height: 18px;
	}

	.input-box {
		position: absolute;
		bottom: 0px;
		left: 0;
		right: 0;
		display: flex;
		padding: 4px 6px;
		box-sizing: border-box;
		height: 53px;
		background: #F9F9F9;
		box-shadow: 0px -2px 4px 0px #EAEAEA;
		display: flex;
		justify-content: center;
		justify-items: center;
		align-items: center;
	}

	.input-box input {
		flex: 1;
		border: 1px #FFFFFF solid;
		background: #FFFFFF;
		border-radius: 3px;
		padding: 3px 4px;
		outline: none;
	}

	.input-box img {
		height: 24px;
		margin: 0px 7px;
	}


	.input-box button {
		background: #2196F4;
		border-radius: 10px;
		border: 1px #fffa solid;
		color: #ffffff;
		margin: 0px 7px;
		height: 24px;
		outline: none;
	}

	button:active {}

	.chart-timer {
		height: 13px;
		font-size: 13px;
		font-family: SourceHanSansCN-Normal, SourceHanSansCN;
		text-align: center;
		color: #CACDD4;
		line-height: 20px;
		margin-bottom: 1rem;

	}

	.iconImg {
		width: 50rpx;
		height: 50rpx;
		margin-right: 18rpx;
	}

	.box {
		position: absolute !important;
		position: relative;
		/*  #ifdef APP-PLUS */
		padding-top: 70px !important;
		/*  #endif  */

		/*  #ifdef H5 */
		padding-top: 48px !important;
		/*  #endif  */

		top: 0;
		bottom: 106rpx;
		width: 100%;
		height: auto !important;
		height: 100%;
		text-align: center;
		overflow: auto;
		background-color: #F9F9F9;
	}



	.loading-box {
		text-align: center;
		position: relative;
		z-index: 100;
	}
</style>
